class WebsocketUtil {
	is_open_socket: boolean;
	url: string;
	data: null;
	timeout: number;
	heartbeatInterval: NodeJS.Timeout | null;
	reconnectTimeOut: NodeJS.Timeout | null;
	socketTask: WebSocket | undefined;
	constructor(url: string, time: number) {
		this.is_open_socket = false; //避免重复连接
		this.url = url; //地址
		this.data = null;
		//心跳检测
		this.timeout = time; //多少秒执行检测
		this.heartbeatInterval = null; //检测服务器端是否还活着
		this.reconnectTimeOut = null; //重连之后多久再次重连
		try {
			this.connectSocketInit();
		} catch (e) {
			console.log("catch");
			this.is_open_socket = false;
			this.reconnect();
		}
	}

	// 进入这个页面的时候创建websocket连接【整个页面随时使用】
	connectSocketInit() {
		this.socketTask = new WebSocket(this.url);
		this.socketTask.onopen = () => {
			clearTimeout(this.reconnectTimeOut!);
			clearTimeout(this.heartbeatInterval!);
			this.start();
			this.is_open_socket = true;
			// 注：只有连接正常打开中 ，才能正常收到消息
			this.socketTask!.onmessage = (res) => {
				const opts = JSON.parse(res.data);
				console.log("接收消息：", opts);
				// 用于页面监听websocket消息
				window.dispatchEvent(
					new CustomEvent("onmessageWS", {
						detail: {
							data: opts
						}
					})
				);
			};
		};
		// 这里仅是事件监听【如果socket关闭了会执行】
		this.socketTask.onclose = () => {
			console.log("已经被关闭了");
			this.is_open_socket = false;
			this.reconnect();
		};
	}

	//发送消息
	socketSend(value: any) {
		// 注：只有连接正常打开中 ，才能正常成功发送消息
		if (this.is_open_socket) {
			console.log("发送传参：", value);
			// websocket的服务器的原理是:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】
			this.socketTask!.send(JSON.stringify(value));
		}
	}
	//开启心跳检测
	start() {
		this.heartbeatInterval = setTimeout(() => {
			const data = { value: "传输内容", method: "方法名称" };
			this.socketSend(data);
		}, this.timeout);
	}
	//重新连接
	reconnect() {
		//停止发送心跳
		clearInterval(this.heartbeatInterval!);
		//如果不是人为关闭的话，进行重连
		if (!this.is_open_socket) {
			this.reconnectTimeOut = setTimeout(() => {
				this.connectSocketInit();
			}, 200);
		}
	}
}

export default WebsocketUtil;
